#include "git-cert-provider.h"

#include <git2/credential.h>
#include <git2/errors.h>

#include "util/logger/logger.h"

#include "git-cert-request.h"

namespace git
{

CertProvider::CertProvider(const Cert &cert)
    : cert_(cert) {
}

git_credential *CertProvider::provide(const CertRequest &req) const {
    if (req.allowSsh()) {
        git_credential *cred = nullptr;
        const char *username = req.usernameFromUrl();
        const std::string publickey = cert_.sshPublicKeyPath().generic_string();
        const std::string privatekey = cert_.sshPrivateKeyPath().generic_string();
        const std::string passphrase = cert_.sshPassphrase();

        if (0 != git_credential_ssh_key_new(
            &cred,
            username,
            publickey.c_str(),
            privatekey.c_str(),
            passphrase.c_str())) {

            LOGE << "git_credential_ssh_key_new error: " << git_error_last()->message;
        }
        return cred;
    }

    if (req.allowUserpass()) {
        git_credential *cred = nullptr;
        const char *username = cert_.httpsUsername().c_str();
        const char *password = cert_.httpsPassword().c_str();
        if (0 != git_credential_userpass_plaintext_new(&cred, username, password)) {
            LOGE << "git_credential_userpass_plaintext_new error: " << git_error_last()->message;
        }
        return cred;
    }

    return nullptr;
}

} // namespace git
